import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import { createPinia } from 'pinia'
import axios from 'axios'
import App from './App.vue'
import './style.css'

// 核心功能页面
import Dashboard from './pages/Dashboard.vue'
import AIChat from './pages/AIChat.vue'
import PolicyCenter from './pages/PolicyCenter.vue'
import CrossBorderAnalysis from './pages/CrossBorderAnalysis.vue'
import PolicyQuery from './pages/PolicyQuery.vue'
import PolicySimulation from './pages/PolicySimulation.vue'
import PolicyMatch from './pages/PolicyMatch.vue'
import RegionCompare from './pages/RegionCompare.vue'
import PolicyPush from './pages/PolicyPush.vue'
import Reminders from './pages/Reminders.vue'
import UserCenter from './pages/UserCenter.vue'
import IntelligentWelcome from './pages/IntelligentWelcome.vue'
import PolicySource from './pages/PolicySource.vue'
import DigitalHuman from './pages/DigitalHuman.vue'

// 工具页面
import PolicyDetail from './pages/PolicyDetail.vue'
import PolicyDiff from './pages/PolicyDiff.vue'
import PolicyTrace from './pages/PolicyTrace.vue'
import PolicyGraph from './pages/PolicyGraph.vue'
import PolicyGene from './pages/PolicyGene.vue'
import ScenarioLogin from './pages/ScenarioLogin.vue'
import ScenarioDemo from './pages/ScenarioDemo.vue'
import BrazilManagerDashboard from './pages/BrazilManagerDashboard.vue'
import OxfordPhDDashboard from './pages/OxfordPhDDashboard.vue'
import EcommerceParkDashboard from './pages/EcommerceParkDashboard.vue'
import MiningCompanyDashboard from './pages/MiningCompanyDashboard.vue'
import PolicySimulationDemo from './pages/PolicySimulationDemo.vue'
import TaxPolicyAnalysisAgent from './pages/TaxPolicyAnalysisAgent.vue'

// 翻译系统
import translateDirective, {
  translatePageContent,
  setCurrentLanguage,
  translateNewContent
} from './directives/translate.js'
import translationService from './services/translationService.js'

// 路由配置
const routes = [
  // 欢迎页面
  { path: '/', component: IntelligentWelcome },
  { path: '/welcome', component: IntelligentWelcome },
  
  // 核心功能页面
  { path: '/dashboard', component: Dashboard, name: 'Dashboard' },
  { path: '/ai-chat', component: AIChat, name: 'AIChat' },
  { path: '/policy-center', component: PolicyCenter, name: 'PolicyCenter' },
  { path: '/cross-border-analysis', component: CrossBorderAnalysis, name: 'CrossBorderAnalysis' },
  { path: '/user-center', component: UserCenter, name: 'UserCenter' },
  { path: '/digital-human', component: DigitalHuman, name: 'DigitalHuman' },
  
  // 工具页面
  { path: '/policy/:id', component: PolicyDetail, name: 'PolicyDetail'},
  { path: '/diff', component: PolicyDiff, name: 'PolicyDiff'},
  { path: '/policy-trace', component: PolicyTrace, name: 'PolicyTrace'},
  
  // 场景页面
  { path: '/scenario-login', component: ScenarioLogin, name: 'ScenarioLogin' },
  { path: '/scenario-demo', component: ScenarioDemo, name: 'ScenarioDemo' },
  { path: '/brazil-manager', component: BrazilManagerDashboard, name: 'BrazilManagerDashboard' },
  { path: '/oxford-phd', component: OxfordPhDDashboard, name: 'OxfordPhDDashboard' },
  { path: '/ecommerce-park', component: EcommerceParkDashboard, name: 'EcommerceParkDashboard' },
  { path: '/mining-company', component: MiningCompanyDashboard, name: 'MiningCompanyDashboard' },
  
  // 税务分析页面
  { path: '/tax-policy-analysis', component: TaxPolicyAnalysisAgent, name: 'TaxPolicyAnalysisAgent' },
  
  // 重定向旧路由到新的整合页面
  //{ path: '/policy-query', redirect: '/policy-center' },
  { path: '/policy-query', component: PolicyQuery },
  { path: '/policy-search', redirect: '/policy-center' },
  { path: '/policy-analysis', redirect: '/policy-center' },
  { path: '/policy-simulation', redirect: '/policy-center' },
  { path: '/policy-match', redirect: '/cross-border-analysis' },
  { path: '/region-compare', redirect: '/cross-border-analysis' },
  { path: '/policy-push', redirect: '/dashboard' },
  { path: '/reminders', redirect: '/dashboard' },
  { path: '/subsidy', redirect: '/policy-center' },
  { path: '/enterprise', redirect: '/cross-border-analysis' },
  { path: '/talent', redirect: '/policy-center' },
  {
    path: '/policy-source',
    name: 'PolicySource',
    component: PolicySource
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

const pinia = createPinia()
const app = createApp(App)

// 注册翻译指令
app.directive('translate', translateDirective)

// 全局属性
app.config.globalProperties.$translate = translationService.translate
app.config.globalProperties.$translatePage = translatePageContent
app.config.globalProperties.$setLanguage = setCurrentLanguage
app.config.globalProperties.$translateNewContent = translateNewContent

// 全局错误处理
app.config.errorHandler = (err, instance, info) => {
  console.error('全局错误:', err, info)
}

// 路由守卫 - 页面切换时处理翻译
router.beforeEach((to, from, next) => {
  console.log(`路由切换: ${from.path} -> ${to.path}`)
  next()
})

router.afterEach(async (to, from) => {
  // 页面切换后，延迟翻译新页面内容
  setTimeout(async () => {
    const currentLang = getCurrentLanguage()
    if (currentLang && currentLang !== 'zh') {
      console.log(`页面切换后翻译内容到 ${currentLang}`)
      await translatePageContent(currentLang)
    }
  }, 500)
})

// 获取当前语言（从localStorage或默认值）
function getCurrentLanguage() {
  try {
    return localStorage.getItem('currentLanguage') || 'zh'
  } catch {
    return 'zh'
  }
}

// 监听语言变化
window.addEventListener('languageChange', async (event) => {
  const newLanguage = event.detail.language
  console.log(`监听到语言变化事件: ${newLanguage}`)

  // 更新翻译指令的当前语言
  setCurrentLanguage(newLanguage)

  // 保存到localStorage
  try {
    localStorage.setItem('currentLanguage', newLanguage)
  } catch (error) {
    console.error('保存语言设置失败:', error)
  }

  // 翻译页面内容
  if (newLanguage !== 'zh') {
    await translatePageContent(newLanguage)
  }
})

// 监听DOM变化，自动翻译新添加的内容
const observer = new MutationObserver(async (mutations) => {
  const currentLang = getCurrentLanguage()
  if (currentLang === 'zh') return

  let hasNewContent = false

  mutations.forEach(mutation => {
    if (mutation.type === 'childList') {
      mutation.addedNodes.forEach(node => {
        if (node.nodeType === Node.ELEMENT_NODE) {
          // 检查是否有新的文本内容
          if (node.textContent && node.textContent.trim()) {
            hasNewContent = true
          }
        }
      })
    }
  })

  // 如果有新内容且不是中文，延迟翻译
  if (hasNewContent) {
    setTimeout(async () => {
      try {
        await translatePageContent(currentLang)
      } catch (error) {
        console.error('自动翻译新内容失败:', error)
      }
    }, 1000)
  }
})

// 启动DOM观察器
observer.observe(document.body, {
  childList: true,
  subtree: true,
  characterData: true
})

// 预翻译常用词汇
async function preTranslateCommonWords() {
  const currentLang = getCurrentLanguage()
  if (currentLang === 'zh') return

  const commonWords = [
    '跨境政策咨询平台', '全球政策概览', '智能咨询', '政策查询', '政策分析',
    '政策匹配', '跨境对比', '政策推送', '定时提醒', '个人中心',
    '欢迎回来', '今天是美好的一天，让我们开始工作吧！',
    '您好！我是您的专属政策咨询助手', '请问有什么可以帮助您的吗？',
    '正在思考中...', '发送', '清空对话', '请输入您的问题...',
    '政策解读', '申请指导', '风险评估', '合规建议',
    '政策总数', '今日更新', '关注地区', '我的收藏',
    '最新政策动态', '热门政策推荐', '个人收藏夹', '系统通知',
    '查看详情', '收藏', '分享', '下载', '打印',
    '加载中...', '搜索', '筛选', '排序', '导出', '导入',
    '确认', '取消', '保存', '删除', '编辑', '添加',
    '成功', '失败', '警告', '信息', '错误'
  ]

  console.log(`预翻译 ${commonWords.length} 个常用词汇到 ${currentLang}`)

  try {
    const promises = commonWords.map(word =>
      translationService.translate(word, currentLang)
    )
    await Promise.all(promises)
    console.log('预翻译完成')
  } catch (error) {
    console.error('预翻译失败:', error)
  }
}

// 应用启动
app.use(pinia)
app.use(router)

// 配置axios
axios.defaults.baseURL = 'http://localhost:8080'
axios.defaults.timeout = 30000

// 请求拦截器
axios.interceptors.request.use(
  config => {
    console.log('发起API请求:', config.method?.toUpperCase(), config.url, config.params || config.data)
    return config
  },
  error => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  response => {
    console.log('API响应成功:', response.config.url, response.status)
    return response
  },
  error => {
    console.error('API请求失败:', error.config?.url, error.response?.status, error.message)
    return Promise.reject(error)
  }
)

// 挂载应用
app.mount('#app')

// 应用启动后的初始化
setTimeout(async () => {
  console.log('应用启动完成，初始化翻译系统')

  // 设置当前语言
  const currentLang = getCurrentLanguage()
  setCurrentLanguage(currentLang)

  // 如果不是中文，预翻译常用词汇
  if (currentLang !== 'zh') {
    await preTranslateCommonWords()
  }

  console.log(`翻译系统初始化完成，当前语言: ${currentLang}`)
}, 1000)